package com.example.rdcproject.ving.notes.service;

import com.example.rdcproject.ving.notes.util.DBUtils;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.LinkedList;

public class ConnectionPool {
    private static ConnectionPool instance;
    private LinkedList<Connection> connections;

    // 配置信息
    private String driver = "com.mysql.cj.jdbc.Driver";

    private int initCount = 5; // 连接池初始大小
    private int maxConnecion = 20; // 连接池最大容量
    private int currentConnection = 0; // 当前连接数

    private ConnectionPool() {
        connections = new LinkedList<>();
        try {
            // 加载数据库驱动
            Class.forName(driver);
            // 初始化连接池
            for (int i = 0; i < initCount; i++) {
                Connection connection = DBUtils.getConnection();
                connections.addLast(connection);
                currentConnection++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //连接池实例化
    public synchronized static ConnectionPool getInstance() {
        if (instance == null) {
            instance = new ConnectionPool();
        }
        return instance;
    }

    //获取连接
    public synchronized Connection getConnection() throws Exception {
        Connection connection = null;
        if (connections.size() > 0) {
            connection = connections.removeFirst();
        } else if (currentConnection < maxConnecion) {
            connection = DBUtils.getConnection();
            currentConnection++;
        }
        return connection;
    }

    //释放连接池
    public  synchronized void releaseConnection(Connection connection) {
        if (connections.size() < initCount) {
            connections.addLast(connection);
        } else {
            try {
                connection.close();
                currentConnection--;
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

